// API基础URL
// 在生产环境中，您可能需要根据实际情况修改这个URL
const API_BASE = 'http://localhost:5000/api';

// 1. 首页引导区 - 平滑滚动
document.getElementById('startBtn').addEventListener('click', () => {
  document.getElementById('structure').scrollIntoView({ behavior: 'smooth' });
});

// 2. 晾房结构互动图解
const structureInfo = document.getElementById('structureInfo');

// 获取结构信息的函数
async function fetchStructureInfo(section) {
  try {
    const response = await fetch(`${API_BASE}/structure/${section}`);
    if (response.ok) {
      const data = await response.json();
      return data;
    } else {
      throw new Error('Network response was not ok.');
    }
  } catch (error) {
    console.error('获取结构信息失败:', error);
    // 使用本地数据作为备选
    const localData = {
      hole: {
        title: "四壁小孔",
        content: "晾房四壁布满菱形小孔（孔径8-10厘米），呈品字形排列。这些小孔能引导空气形成穿堂风，是葡萄干燥的核心动力，每天可带走葡萄5%左右的水分。"
      },
      frame: {
        title: "木架系统",
        content: "内部木架分3-4层，用本地杨木或柳木制成。每层间距1.2-1.5米，上层通风最佳（5-7天干燥），下层湿度稍高（适合晚熟葡萄），避免阳光直射导致葡萄变质。"
      },
      roof: {
        title: "屋顶通风口",
        content: "尖顶设计便于排水，顶部预留通风口，与四壁小孔形成垂直气流循环，加速热空气排出，保持晾房内干燥凉爽的环境。"
      }
    };
    return localData[section];
  }
}

// 显示结构信息
async function showStructureInfo(section) {
  const data = await fetchStructureInfo(section);
  if (data) {
    structureInfo.innerHTML = `
      <h4 class="text-lg font-bold mb-2 text-wood">${data.title}</h4>
      <p class="text-gray-700">${data.content}</p>
    `;
  }
}

// 绑定热点点击事件
document.getElementById('holeHotspot').addEventListener('click', () => showStructureInfo('hole'));
document.getElementById('frameHotspot').addEventListener('click', () => showStructureInfo('frame'));
document.getElementById('roofHotspot').addEventListener('click', () => showStructureInfo('roof'));

// 3. 晾晒步骤时间轴
// 步骤切换
const stepBtns = document.querySelectorAll('.step-btn');
const stepContents = document.querySelectorAll('.step-content');

stepBtns.forEach(btn => {
  btn.addEventListener('click', () => {
    const step = btn.getAttribute('data-step');
    
    // 更新按钮样式
    stepBtns.forEach(b => {
      b.classList.remove('active', 'bg-wood', 'text-white');
      b.classList.add('bg-earth/50', 'text-gray-700');
    });
    btn.classList.add('active', 'bg-wood', 'text-white');
    btn.classList.remove('bg-earth/50', 'text-gray-700');
    
    // 显示对应内容
    stepContents.forEach(content => content.classList.add('hidden'));
    document.getElementById(`step${step}`).classList.remove('hidden');
  });
});

// 采摘步骤弹窗
const pickInfoBtn = document.getElementById('pickInfoBtn');
const pickModal = document.getElementById('pickModal');
const pickModalOverlay = document.getElementById('pickModalOverlay');

if (pickInfoBtn && pickModal && pickModalOverlay) {
  pickInfoBtn.addEventListener('click', () => pickModal.classList.remove('hidden'));
  pickModalOverlay.addEventListener('click', () => pickModal.classList.add('hidden'));
}

// 挂架步骤拖拽交互
const dragArea = document.getElementById('dragArea');
if (dragArea) {
  const dragItems = dragArea.querySelectorAll('.drag-item');
  const dragHint = document.getElementById('dragHint');
  
  let draggedItem = null;
  
  dragItems.forEach(item => {
    item.addEventListener('dragstart', () => {
      draggedItem = item;
      setTimeout(() => item.classList.add('opacity-50'), 0);
    });
    
    item.addEventListener('dragend', () => {
      item.classList.remove('opacity-50');
      draggedItem = null;
      checkOverlap();
    });
  });
  
  dragArea.addEventListener('dragover', e => {
    e.preventDefault();
    const afterElement = getDragAfterElement(dragArea, e.clientY);
    if (afterElement == null) {
      dragArea.appendChild(draggedItem);
    } else {
      dragArea.insertBefore(draggedItem, afterElement);
    }
  });
  
  function getDragAfterElement(container, y) {
    const draggableElements = [...container.querySelectorAll('.drag-item:not(.opacity-50)')];
    return draggableElements.reduce((closest, child) => {
      const box = child.getBoundingClientRect();
      const offset = y - box.top - box.height / 2;
      if (offset < 0 && offset > closest.offset) {
        return { offset: offset, element: child };
      } else {
        return closest;
      }
    }, { offset: Number.NEGATIVE_INFINITY }).element;
  }
  
  function checkOverlap() {
    const items = [...dragArea.querySelectorAll('.drag-item')];
    let overlap = false;
    
    items.forEach((item, i) => {
      const nextItem = items[i + 1];
      if (nextItem) {
        const rect1 = item.getBoundingClientRect();
        const rect2 = nextItem.getBoundingClientRect();
        if (rect1.right > rect2.left) overlap = true;
      }
    });
    
    if (dragHint) {
      dragHint.classList.toggle('hidden', !overlap);
    }
  }
}

// 干燥步骤滑块交互
const dryingSlider = document.getElementById('dryingSlider');
const dryingImg = document.getElementById('dryingImg');
const dryingDesc = document.getElementById('dryingDesc');

if (dryingSlider && dryingImg && dryingDesc) {
  const dryingData = IMAGE_CONFIG.drying;
  
  dryingSlider.addEventListener('input', () => {
    const day = parseInt(dryingSlider.value);
    // 匹配最接近的天数数据
    const closest = dryingData.reduce((prev, curr) => 
      (Math.abs(curr.day - day) < Math.abs(prev.day - day) ? curr : prev)
    );
    
    dryingImg.src = closest.img;
    dryingDesc.textContent = closest.desc;
  });
}

// 分拣步骤交互
const sortingArea = document.getElementById('sortingArea');
if (sortingArea) {
  const sortItems = sortingArea.querySelectorAll('.sort-item');
  const sortingResult = document.getElementById('sortingResult');
  let badCount = 0;
  const totalBad = 2;
  
  sortItems.forEach(item => {
    item.addEventListener('click', () => {
      if (item.classList.contains('sorted')) return;
      
      item.classList.add('sorted', 'opacity-50');
      if (item.getAttribute('data-quality') === 'bad') {
        badCount++;
        item.classList.add('ring-2', 'ring-red-500');
      } else {
        item.classList.add('ring-2', 'ring-green-500');
      }
      
      if (sortingResult) {
        sortingResult.textContent = `已挑出 ${badCount}/${totalBad} 个不合格果实`;
      }
    });
  });
}

// 成品步骤品种切换
const varietyBtns = document.querySelectorAll('.variety-btn');
const varietyInfo = document.getElementById('varietyInfo');

const varietyData = {
  white: {
    name: "无核白葡萄干",
    desc: "最常见的品种，果肉晶莹剔透，甜度高达24%-26%，适合直接食用或烘焙。"
  },
  red: {
    name: "红香妃葡萄干",
    desc: "果肉呈浅红色，带有淡淡玫瑰香，颗粒较大（长约2厘米），富含花青素。"
  },
  black: {
    name: "黑加仑葡萄干",
    desc: "紫黑色果皮，果肉酸甜适中，富含维生素C和抗氧化物质，适合泡水或做果酱。"
  }
};

varietyBtns.forEach(btn => {
  btn.addEventListener('click', () => {
    const variety = btn.getAttribute('data-variety');
    const data = varietyData[variety];
    
    // 更新按钮样式
    varietyBtns.forEach(b => {
      b.classList.remove('active', 'bg-grape', 'text-white');
      b.classList.add('bg-grape/30', 'text-gray-700');
    });
    btn.classList.add('active', 'bg-grape', 'text-white');
    btn.classList.remove('bg-grape/30', 'text-gray-700');
    
    // 更新信息
    if (varietyInfo) {
      varietyInfo.innerHTML = `
        <h4 class="font-bold text-grape">${data.name}</h4>
        <p class="text-sm">${data.desc}</p>
      `;
    }
  });
});

// 4. 互动模拟游戏
const windLevel = document.getElementById('windLevel');
const dayLevel = document.getElementById('dayLevel');
const startGameBtn = document.getElementById('startGameBtn');
const gameGrapeImg = document.getElementById('gameGrapeImg');
const gameResult = document.getElementById('gameResult');
const resultTitle = document.getElementById('resultTitle');
const resultDesc = document.getElementById('resultDesc');

// 获取游戏结果的函数
async function fetchGameResult(wind, days) {
  try {
    const response = await fetch(`${API_BASE}/game/result`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        wind_level: wind,
        day_level: days
      })
    });
    
    if (response.ok) {
      const data = await response.json();
      return data;
    } else {
      throw new Error('Network response was not ok.');
    }
  } catch (error) {
    console.error('游戏结果获取失败:', error);
    // 使用本地逻辑作为备选
    let result, title, desc, img;
    
    if (wind >= 3 && wind <= 5 && days >= 10 && days <= 15) {
      result = "success";
      title = "优质葡萄干！";
      desc = `恭喜！你用${wind}级通风和${days}天，晾晒出了含水量15%的优质葡萄干`;
      img = IMAGE_CONFIG.game.success;
    } else if (wind < 3) {
      result = "fail";
      title = "晾晒失败";
      desc = `通风不足（仅${wind}级），葡萄霉变了！晾房需要足够的穿堂风才能防止发霉`;
      img = IMAGE_CONFIG.game.fail_mold;
    } else if (days < 10) {
      result = "fail";
      title = "晾晒不足";
      desc = `${days}天时间太短，葡萄还没干透（水分含量>30%），容易变质`;
      img = IMAGE_CONFIG.game.fail_under;
    } else {
      result = "fail";
      title = "过度晾晒";
      desc = `${days}天时间太长，葡萄干变得干硬，失去了柔软口感`;
      img = IMAGE_CONFIG.game.fail_over;
    }
    
    return {
      title: title,
      description: desc,
      image: img
    };
  }
}

// 开始游戏
if (startGameBtn) {
  startGameBtn.addEventListener('click', async () => {
    if (!windLevel || !dayLevel || !gameGrapeImg || !gameResult || !resultTitle || !resultDesc) return;
    
    const wind = parseInt(windLevel.value);
    const days = parseInt(dayLevel.value);
    
    const result = await fetchGameResult(wind, days);
    
    // 更新结果
    gameGrapeImg.src = result.image;
    resultTitle.textContent = result.title;
    resultDesc.textContent = result.description;
    gameResult.classList.remove('hidden');
    
    // 3秒后隐藏结果（可再次尝试）
    setTimeout(() => gameResult.classList.add('hidden'), 3000);
  });
}

// 动态设置图片
function setImages() {
  // 首页背景图
  const homeBackground = document.getElementById('homeBackground');
  if (homeBackground) {
    homeBackground.src = IMAGE_CONFIG.homeBackground;
  }
  
  // 晾房结构图
  const structureImg = document.getElementById('structureImg');
  if (structureImg) {
    structureImg.src = IMAGE_CONFIG.structure;
  }
  
  // 制作步骤图片
  const pickingImg = document.getElementById('pickingImg');
  if (pickingImg) {
    pickingImg.src = IMAGE_CONFIG.steps.picking;
  }
  
  const hangingImg = document.getElementById('hangingImg');
  if (hangingImg) {
    hangingImg.src = IMAGE_CONFIG.steps.hanging;
  }
  
  const sortingImg = document.getElementById('sortingImg');
  if (sortingImg) {
    sortingImg.src = IMAGE_CONFIG.steps.sorting;
  }
  
  const finishedImg = document.getElementById('finishedImg');
  if (finishedImg) {
    finishedImg.src = IMAGE_CONFIG.steps.finished;
  }
  
  // 采摘标准对比图
  const properGrapeImg = document.getElementById('properGrapeImg');
  if (properGrapeImg) {
    properGrapeImg.src = IMAGE_CONFIG.pickingStandards.proper;
  }
  
  const overripeGrapeImg = document.getElementById('overripeGrapeImg');
  if (overripeGrapeImg) {
    overripeGrapeImg.src = IMAGE_CONFIG.pickingStandards.overripe;
  }
  
  // 挂架拖拽演示图
  const grapeBunch1 = document.getElementById('grapeBunch1');
  if (grapeBunch1) {
    grapeBunch1.src = IMAGE_CONFIG.hangingDemo;
  }
  
  const grapeBunch2 = document.getElementById('grapeBunch2');
  if (grapeBunch2) {
    grapeBunch2.src = IMAGE_CONFIG.hangingDemo;
  }
  
  // 知识拓展区图片
  const climateImg = document.getElementById('climateImg');
  if (climateImg) {
    climateImg.src = IMAGE_CONFIG.knowledge.climate;
  }
  
  const comparisonImg = document.getElementById('comparisonImg');
  if (comparisonImg) {
    comparisonImg.src = IMAGE_CONFIG.knowledge.comparison;
  }
  
  const nutritionImg = document.getElementById('nutritionImg');
  if (nutritionImg) {
    nutritionImg.src = IMAGE_CONFIG.knowledge.nutrition;
  }
  
  // 初始化干燥图片为第一天
  const dryingImg = document.getElementById('dryingImg');
  if (dryingImg && IMAGE_CONFIG.drying.length > 0) {
    dryingImg.src = IMAGE_CONFIG.drying[0].img;
  }
}

// 页面加载完成后设置图片
document.addEventListener('DOMContentLoaded', setImages);

// 页面滚动动画
window.addEventListener('scroll', () => {
  const sections = document.querySelectorAll('section');
  sections.forEach(section => {
    const rect = section.getBoundingClientRect();
    if (rect.top < window.innerHeight * 0.75) {
      section.classList.add('fade-in');
    }
  });
});